const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'productManage';



function _connectDb(callback) {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
        assert.equal(null, err);
        console.log("Connected successfully to server");
        const db = client.db(dbName);
        callback(db,err, client);
       
    });
};

function mongoFind(collecName, json, cb) {

    _connectDb(function (db, err, client) {
        const collection = db.collection(collecName);
        collection.find(json).toArray(function (err, docs) {
            assert.equal(err, null);
            console.log("Found the following records");
            cb(docs)
            client.close()
        })
    })
};

function mongoInsert(collecName, json, cb){
    _connectDb(function (db, err, client) {
        const collection = db.collection(collecName);
        collection.insertMany(json, function(err, result) {
            assert.equal(err, null);
            callback(result);
          });
    })
}


function insert() { }

module.exports = {
    mongoFind,
    mongoInsert
}